// Vue3概念：通过组合式API封装 数据逻辑 在一起的函数，组合式函数 useXxx
// composable
import { all as categoryAll } from "@/services/category";
import { all as docAll } from "@/services/doc";
import type { Category, CategoryList } from "@/types/category";
import type { Doc, DocList } from "@/types/doc";
import { ref } from "vue";

// 扁平化数组转树形结构
type ItemType = { id?: number; parent?: number; children?: DocList };
export const attr2Tree = <T extends ItemType>(arr: T[], parent: number) => {
  const data: T[] = [];
  arr.forEach((item) => {
    if (item.parent === parent) {
      item.children = attr2Tree(arr, item.id!);
      data.push(item);
    }
  });
  return data;
};
// 获取分类树
export const useGetCategoryListTree = () => {
  const categoryListTree = ref<CategoryList>([]);
  const getCategoryListTree = async () => {
    const res = await categoryAll();
    categoryListTree.value = attr2Tree<Category>(res.content, 0);
  };
  return {
    categoryListTree,
    getCategoryListTree,
  };
};
// 获取文档树
export const useGetDocListTree = (ebookId: number) => {
  const docListTree = ref<DocList>([]);
  const docListTreeRemoveParent = ref<DocList>([]);
  const getDocListTree = async () => {
    const res = await docAll(ebookId);
    docListTree.value = attr2Tree<Doc>(res.content, 0);
    //  处理树形组件parent属性bug
    docListTreeRemoveParent.value = attr2Tree<Doc>(JSON.parse(JSON.stringify(res.content)), 0);
    const removeParentProperty = (nodes: DocList) => {
      nodes.forEach((node) => {
        delete node.parent;
        if (node.children && node.children.length) {
          removeParentProperty(node.children);
        }
      });
    };
    removeParentProperty(docListTreeRemoveParent.value);
  };
  return {
    docListTree,
    docListTreeRemoveParent,
    getDocListTree,
  };
};
